<!-- 表单的标签组件 -->
<template>
  <div class="flex gap-2">
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag"
      closable
      :type="tagType"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      class="w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="small" @click="showInput">
      + New Tag
    </el-button>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, onMounted, watch } from "vue";
import { ElInput } from "element-plus";
import type { InputInstance } from "element-plus";
import { computed } from "vue";

const props = defineProps({
  dynamicTags: {
    type: String,
    default: () => `["Tag 1", "Tag 2", "Tag 3"]`,
  },
  // Tag 的类型
  tagType: {
    type: String,
    default: "primary",
  },
});

const inputValue = ref("");
// 标签数组
const dynamicTags = ref<string[]>([]);

const inputVisible = ref(false);
const InputRef = ref<InputInstance>();

const emit = defineEmits(["addTag"]);

// 初始化 dynamicTags
onMounted(() => {
  // 将json字符串转为数组，添加空值检查
  try {
    dynamicTags.value = JSON.parse(props.dynamicTags || "[]");
  } catch (error) {
    console.error("Invalid JSON string for dynamicTags:", props.dynamicTags);
    dynamicTags.value = [];
  }
});

// 在onMounted生命周期后添加数据监听
watch(
  () => props.dynamicTags,
  (newVal) => {
    try {
      dynamicTags.value = JSON.parse(newVal || "[]");
    } catch (e) {
      dynamicTags.value = [];
    }
  },
  { deep: true, immediate: true }
);

// 删除标签
const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

// 添加标签
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
// 确认标签
const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";

  // 将数据转换为jso数组字符串
  emit("addTag", JSON.stringify(dynamicTags.value));
};
</script>
